package com.itcm.skymail.product.exception;

import com.itcm.common.exception.BizCodeEnum;
import com.itcm.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

/**
 * 描述: 统一异常处理
 *
 * @author cm_fighting
 * @create 2020-09-15 2:10 下午
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.itcm.skymail.product.controller")
public class SkymailExceptionControllerAdvice {

    // 精确异常处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常：{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        HashMap<String, String> map = new HashMap<>();
        fieldErrors.forEach(item -> {
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    // 通用异常处理， 如果有精确异常处理 会先找精确异常处理
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error(e.getMessage());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
